 
import { depoColldown } from "utils/constants/definetypes";
import { APollingTask, CacheData } from "../../PollingStation";
import { cache_return } from "utils/decorate/decorate";

export class CacheDataEvent<T extends MyEventItem=MyEventItem> extends CacheData<T>
{
    private event_record:Record<EventConstant,MyEventItem[]>={} as any ;
    private destory_events:Record<EventDestroyType,MyEventItem[]>={} as any;
    constructor(Tdata:Array<T>)
    {
        super(Tdata);
        this.Init(Tdata);
    }

    private Init(Tdata:Array<T>)
    {
        this.event_record= _.groupBy(Tdata,e=>e.event) as any;

        const events = this.event_record[EVENT_OBJECT_DESTROYED ] as MyEventItem<EVENT_OBJECT_DESTROYED>[];
        if(events)
        {
            this.destory_events = _.groupBy(events,e=>e.data.type) as any;
        }

    }

    public inquireEvent<V extends EventConstant>(eventVal:V):MyEventItem<V>[]|undefined
    {
        return this.event_record[eventVal]as MyEventItem<V>[];
    }

    public inquireStructureDestory(type:EventDestroyType)
    {
        return this.destory_events[type];
    }

    // 判断是否被攻击了
    @cache_return("cache",0)
    public isBeAttacked()
    {
        const events = this.inquireEvent(EVENT_ATTACK);
        if(!events)
        {
            return false;
        }
        for(const e of events)
        {
            const obj = Game.getObjectById(e.objectId as (Id<OwnedStructure|Creep>));
            let target = Game.getObjectById(e.data.targetId as (Id<OwnedStructure|Creep>));
            if( target?.owner?.username == global.UserName)
            {
                return target;
            }
        }
        return false;
    }


    @cache_return("cache",0)
    public getAttacker<T extends OwnedStructure|Creep>()
    {
        const events = this.inquireEvent(EVENT_ATTACK);
        if(!events)
        {
            return false;
        }
        const rets=[]
        for(const e of events)
        {
            const obj = Game.getObjectById(e.objectId as (Id<T>));
            if(obj)
            {
                rets.push(obj)
            }
            
        }
        if(rets.length)
        {
            return rets;
        }
        return false;
    }
}

export class CacheEventTask<T = CacheDataEvent<EventItem>> extends APollingTask<T>
{
    // roomName!:string;实时日志没Tick刷新

    Update(...arg:any[]): void
    {
        // this.roomName = arg[0];

        const room = Game.rooms[this.code];
        
        if(room)
        {
            // EVENT_OBJECT_DESTROYED 这个有bug只能检测到爬
            const events = room.getEventLog();
            this.value = new CacheDataEvent<EventItem>(events) as unknown as  T;
            this.lastupdate = Game.time;
        }
        else
        {
            this.value =undefined;
        }
    }

}
